package server.thread;

import server.model.Request;
import server.model.Response;
import server.servlet.HttpServlet;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String, Map<String, HttpServlet>> map;
    private Map<String, String> staticMap;

    public RequestProcessor(Socket socket, Map<String, Map<String, HttpServlet>> map, Map<String, String> staticMap) {
        this.socket = socket;
        this.map = map;
        this.staticMap = staticMap;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            String url = request.getUrl();
            String[] split = url.split("/");
            String hostName = split[1];
            String servletUrl = split[2];
            // 静态资源处理
            if(url.contains(".html")
                    || url.contains(".jsp")
                    || map.get(hostName) == null
                    || map.get(hostName).get("/" + servletUrl) == null) {
                if(split.length > 3){
                    response.outputHtml(staticMap.get(hostName) + "/" + split[3]);
                }
                response.outputHtml(staticMap.get(hostName));
            }else{
                // 动态资源servlet请求
                HttpServlet httpServlet = map.get(hostName).get("/" + servletUrl);
                httpServlet.service(request,response);
            }

            socket.close();

        }catch (Exception e) {
            e.printStackTrace();
        }

    }
}
